package cluster

import (
	"context"
	"encoding/base64"
	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"krm_backend/config"
	"krm_backend/utils/logs"
)

type ClusterInfo struct {
	Id          string `json:"id"`
	DisplayName string `json:"displayName"`
	City        string `json:"city"`
	District    string `json:"district"`
}

type ClusterConfig struct {
	ClusterInfo
	Kubeconfig string `json:"kubeconfig"`
}

// 定义结构体，用户描述集群信息
type ClusterStatus struct {
	ClusterInfo
	Version string `json:"version"`
	Status  string `json:"status"`
}

// 判断集群状态
func (c *ClusterConfig) GetClusterStatus() (ClusterStatus, error) {
	// 判断集群是否真诚
	clusterStatus := ClusterStatus{}
	clusterStatus.ClusterInfo = c.ClusterInfo
	// 对Kubeconfig先base64解码
	kubeconfigBytes, err := base64.StdEncoding.DecodeString(c.Kubeconfig)
	if err != nil {
		logs.Error(nil, "解码base64失败")
		return clusterStatus, err
	}
	// 创建一个clientSet
	restConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfigBytes)
	if err != nil {
		return clusterStatus, err
	}
	clientSet, err := kubernetes.NewForConfig(restConfig)
	if err != nil {
		return clusterStatus, err
	}
	serverVersion, err := clientSet.Discovery().ServerVersion()
	if err != nil {
		return clusterStatus, err
	}
	clusterVersion := serverVersion.String()
	clusterStatus.Version = clusterVersion
	clusterStatus.Status = "Active"
	return clusterStatus, nil
}

func addOrUpdate(r *gin.Context, method string) {
	var arg string
	if method == "Create" {
		arg = "添加"
	} else {
		arg = "更新"
	}
	// 实例化clusterConfig
	clusterConfig := ClusterConfig{}
	returnData := config.NewReturnData()
	if err := r.ShouldBindJSON(&clusterConfig); err != nil {
		msg := arg + "集群的配置信息不完整: " + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	}
	logs.Info(map[string]interface{}{"集群名称": clusterConfig.DisplayName, "集群ID": clusterConfig.Id}, "开始"+arg+"集群")
	// 创建一个集群配置的secret
	var clusterConfigSecret corev1.Secret
	clusterConfigSecret.Name = clusterConfig.Id
	clusterConfigSecret.Labels = make(map[string]string)
	clusterConfigSecret.Labels["kubeasy.com/cluster.metadata"] = "true"
	// 添加注解 保存集群的配置信息
	clusterConfigSecret.Annotations = make(map[string]string)
	clusterConfigSecret.Annotations["displayName"] = clusterConfig.DisplayName
	clusterConfigSecret.Annotations["city"] = clusterConfig.City
	clusterConfigSecret.Annotations["district"] = clusterConfig.District
	// 保存kubeconfig
	clusterConfigSecret.StringData = make(map[string]string)
	clusterConfigSecret.StringData["kubeconfig"] = clusterConfig.Kubeconfig

	// 创建secret
	var err error
	if method == "Create" {
		_, err = config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).Create(context.TODO(), &clusterConfigSecret, metav1.CreateOptions{})
	} else {
		_, err = config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).Update(context.TODO(), &clusterConfigSecret, metav1.UpdateOptions{})
	}
	if err != nil {
		logs.Error(map[string]interface{}{"集群Id": clusterConfig.Id, "集群名字": clusterConfig.DisplayName, "msg": err.Error()}, arg+"集群失败")
		msg := arg + "集群失败" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	}
	
	// 保存集群信息
	config.ClusterKubeconfig[clusterConfig.Id] = clusterConfig.Kubeconfig

	logs.Info(map[string]interface{}{"集群ID": clusterConfig.Id, "集群名字": clusterConfig.DisplayName}, arg+"集群成功")
	returnData.Status = 200
	returnData.Message = arg + "成功"
	r.JSON(200, returnData)
}
